package org.dg.dgimg.utils;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Slf4j
@Component
public class EmailUtils {

    @Autowired
    JavaMailSender sender;

    public Map<String,String> sendEmail(String to) {
        Map<String,String> map = new HashMap<String,String>();
        Random random = new Random();
        int randomNumber = 100000 + random.nextInt(900000); // 生成一个6位数的随机数
        // 创建一个复杂邮件消息
        MimeMessage message = sender.createMimeMessage();
        map.put("email", to);
        map.put("code", randomNumber + "");
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom("superhub0836@163.com");
            helper.setTo(to);
            helper.setSubject(" \uD83C\uDF33 验证码提醒");

            // 设置邮件内容
            String content = "<!doctype html>\n" +
                    "<html>\n" +
                    "<head>\n" +
                    "<meta charset='UTF-8'><meta name='viewport' content='width=device-width initial-scale=1'>\n" +
                    "<title>邮件</title>\n" +
                    "</head>\n" +
                    "<body><h1 id='验证码提醒'>验证码提醒 \uD83D\uDC0E "+randomNumber+"</h1>"  +
                    "<h3 id='亲爱的用户'><strong> \uD83D\uDE18 亲爱的用户：</strong></h3>\n" +
                    "<p>您正在进行邮箱验证，您的 \uD83D\uDD25 <strong>验证码</strong>是：<em><strong>【 \uD83D\uDC0E" + randomNumber + "\uD83D\uDC0E 】</strong></em>，验证码会在 \uD83D\uDD25 <strong>3分钟</strong> \uD83D\uDD25 之内有效。</p>\n" +
                    "<p>为了保证您的账号安全，请勿向他人泄露此验证码。</p>\n" +
                    "<p>此致</p>\n" +
                    "<p>\uD83D\uDCEC DGIMG</p>\n" +
                    "</body>\n" +
                    "</html>";

            helper.setText(content, true); // true 表示这是一个 HTML 内容的邮件

            // 发送邮件
            sender.send(message);
            return map;
        } catch (MessagingException e) {
            log.error("EmailUtils sandEmail erro"+e.getMessage());
            return null;
        }
    }
}
